package raft

import (
	"math/rand"
	"net/rpc"
	"sync"
	"sync/atomic"
	"time"
)

type Raft struct {
	mu    sync.Mutex
	peers []*rpc.Client // 访问同层节点的Client, 每个peer上运行rpc.Server
	me    int
	dead  int32
}

func (rf *Raft) GetState() (int, bool) {
}

type RequestVoteArgs struct {
}

type RequestVoteReply struct {
}

func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {

}

func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {
	err := rf.peers[server].Call("Raft.RequestVote", args, reply)
	return err == nil
}

func (rf *Raft) Start(command any) (int, int, bool) {
	index := -1
	term := -1
	isLeader := true

	return index, term, isLeader
}

func (rf *Raft) Kill() {
	atomic.StoreInt32(&rf.dead, 1)
}

func (rf *Raft) killed() bool {
	z := atomic.LoadInt32(&rf.dead)
	return z == 1
}

func (rf *Raft) ticker() {
	for rf.killed() == false {
		ms := 50 + (rand.Int63() % 300)
		time.Sleep(time.Duration(ms) * time.Millisecond)
	}
}

func NewRaft(peers []*rpc.Client, me int) *Raft {
	rf := &Raft{
		peers: peers,
		me:    me,
	}

	go rf.ticker()
	return rf
}
